import React, { useState, useEffect, useRef, useMemo } from 'react';
import { toast, setSessionItem, loginData, backgroundObj, dataParams, setString, goBack } from '@/utils/utils';
// import loading from '@/assert/image/live_icon1.png';
import Taro, { useDidShow, useDidHide } from '@tarojs/taro';
import Tab from '@/components/Tabs';
import { View, Input, Text, Video, RichText, ScrollView } from '@tarojs/components'
import { handleLink } from '@/utils/utils'
import { getCurrentInstance } from '@tarojs/taro'
import SuspendedGoods from './components/SuspendedGoods';
import Contain from './components/liveContain';
import ShareImageComponent from '@/components/ShareImage';
import CountdownTimer from './components/CountdownTimer';
import Lottery from './components/Lottery';
import MaskPrize from './components/MaskPrize';
import MaskPeople from './components/MaskPeople';
import ToolPop from './components/ToolPop';
import Invitation from './components/Invitation';
import MaskGift from './components/MaskGift';
import MaskCollection from './components/MaskCollection'
import Recommendation from './components/Recommendation';
import { fetchGoodsDetail, fetchUserGoodsCommerce, fakeInBlackList, fetchShareInfo } from '@/server/shop';
import { fetchUserNeedInformationCollection } from '@/server/order'
import HorizontalUi from './components/HorizontalUi'
import { formatRichText } from '@/utils/utils';
import Router from '@/utils/router';
import RenderChatRoom from './components/RenderRoom'
import "taro-ui/dist/style/components/icon.scss";
import 'taro-ui/dist/style/components/accordion.scss'
import { AtAccordion, AtList, AtListItem, AtTag } from 'taro-ui'
import 'taro-ui/dist/style/components/accordion.scss'
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/tag.scss";
import { fetchCheckMiniProgramUpdate } from '@/server/shop';
import { CopyToClipboard } from '@/utils/utils'
import './index.scss';
let headerTime = null;
let TaskSocket = null
const LiveInteraction = (props) => {
  const { params = {} } = getCurrentInstance().router || {}
  const { goodsType, goodsId, openType } = params
  const [active, setActive] = useState('js');
  const [blackListFlag, setBlackListFlag] = useState('0')
  const [playerList, setPlayerList] = useState([])
  const [videoPlayIndex, setVideoPlayIndex] = useState(0)
  const [account, setAccout] = useState(Taro.getStorageSync("userInfo"))
  const [messages, setMessages] = useState([]);
  const [visibleSuspende, setVisibleSuspende] = useState(false)
  const [liveInfo, setLiveInfo] = useState({})
  const [socketFalg, setSocketFlag] = useState(false)
  const [check, setCheck] = useState('1')
  const [session, setSession] = useState(null)
  const [inputValue, setInputValue] = useState('');
  const [data, setData] = useState({})
  const [visible, setVisible] = useState(false)
  const [useData, setUseData] = useState({})
  const [lotteryData, setLotteryData] = useState({})
  const [LotteryVisible, setLotteryVisible] = useState(false)
  const [peopleVisible, setPeopleVisible] = useState(false)
  const [playerRead, setPlayerRead] = useState(true)
  const [visibleShare, setVisibleShare] = useState(false)
  const [appointFlag, setAppointFlag] = useState(false)
  const [prizeVisible, setPirzeVisible] = useState(false)
  const [toolPopVisible, setToolPopVisible] = useState(false)
  const [giftVisible, setGiftVisible] = useState(false)
  const [recommendationVisible, setRecommendationVisible] = useState(false)
  const [collection, setCollection] = useState({})
  const [renderStyle, setRenderStyle] = useState('default')
  const [renderSelf, setRenderSelft] = useState('sp')
  const [materialInfoVisible, setMaterialInfoVisible] = useState(true)
  const { username, unionId, openId, organizationId, profile, token } = account
  const { goodsBaseInfo = {}, directLiveInfo
    = {}, mainAdminInfo = {}, goodsCommerceList = [], materialInfoList = [] } = data
  const { content, picture } = goodsBaseInfo
  const { playUrl, liveStatus, warmUp, warmUpType, startTime, commerceGoodsAmount = 0, screenType } = directLiveInfo
  const { profile: img, username: name
  } = mainAdminInfo
  const { lotteryInfo = {} } = lotteryData
  const fetchList = () => {
    fetchUserGoodsCommerce({ goodsId, organizationId }).then(val => {
      const { goodsCommerceList = [] } = val
      setVisible({
        show: true,
        detail: goodsCommerceList
      })
    })

  }
  const fetchData = () => {
    fetchGoodsDetail({ organizationId, goodsId }).then(e => {
      const { otteryInfo = {}, prizeList = [], directLiveInfo = {}, liveInfo
        = {}, replayInfoList = [] } = e
      setLotteryData({ lotteryInfo, prizeList })
      setData({
        ...e,
        directLiveInfo: {
          ...directLiveInfo,
          ...liveInfo
        }
      })
      setPlayerList(replayInfoList.reduce((item, val) => {
        const { replayUrl } = val
        return [...item, JSON.parse(replayUrl).map(item => { return item.playUrl })[0]]
      }, []))
    })
  }
  const fetchUserNeedInformation = () => {
    fetchUserNeedInformationCollection({ unionId, organizationId, goodsId, informationCollectionPage: 'pageLive', }).then(e => {
      const { checkInformationCollection = {}, informationCollection = {} } = e
      const { needFlag } = checkInformationCollection
      const { editFlag } = informationCollection
      setCollection({
        show: needFlag === '1' && openType !== 'gzh',
        detail: informationCollection
      })
    })
  }
  useDidShow(() => {
    setSessionItem({
      goodsId, goodsType,
      fromGoodsId: goodsId
    })
    setAccout(Taro.getStorageSync("userInfo"))
    disconnect()
  })

  const { realTimeCount } = useData
  const { status, } = liveInfo
  let liveObjStatus = status ? status : liveStatus
  useEffect(() => {
    connect();
    fakeInBlackList({
      organizationId, unionId, goodsId
    }).then(e => {
      const { blackListFlag = '0' } = e
      if (blackListFlag === '0') {
        fetchData()
      }
      else {
        toast('您已被拉黑，3秒后退出直播')
        let timeOut = setTimeout(() => {
          Router('user', {
            linkType: 'reLaunch'
          })
          clearTimeout(timeOut)
        }, 3000)
        setBlackListFlag(blackListFlag)
      }
    })
    // fetchUserNeedInformation()
    return () => {
      disconnect()
    }
  }, []);
  useEffect(() => {
    fetchCheckMiniProgramUpdate().then(val => {
      const { needUpdate } = val
      setCheck(needUpdate)
    })
  }, [])
  const list = [

    // { label: '导师发言', value: 'ds' },
    { label: '直播详情', value: 'js' },
    { label: '资料', show: materialInfoList.length > 0, value: 'materialInfo' },
  ];
  const renderIcon = (type, url) => {

    if (type === 'image') {
      return 'file-png'
    } else if (type === 'video') {
      return 'file-video'
    } else if (type === 'voice') {
      return 'file-audio'
    }
    else if (type === 'ebook') {
      return 'file-new'
    } else {
      function getFileExtension(fileName) {
        // 使用正则表达式匹配文件名中的后缀部分
        const regex = /(?:\.([^.]+))?$/;
        const result = regex.exec(fileName);

        // 提取匹配到的后缀，如果没有后缀则返回空字符串
        const extension = result ? result[1] : '';

        return extension;
      }
      return `file-${getFileExtension(url)}`
    }
  }
  const connect = () => {
    const { username, unionId, openId, organizationId, profile, token } = Taro.getStorageSync("userInfo")
    let createSession = null
    createSession = session || setString(true, 1, 18)
    setSession(createSession)
    Taro.connectSocket({
      url: `${WSSReplayURL}?${dataParams({
        ...account,
        userSession: createSession, sessionId: createSession, senderType: 'user', goodsId, username, profile, messageType: 'student', organizationId, device: 'miniProgram', token, unionId, goodsType
      })}`,
    }).then(val => {
      TaskSocket = val
      val.onOpen(() => {
        setSocketFlag(true)
        heartBeatStart()
      })
      val.onError((err) => {
        console.log(err, 'websocket发生错误')
        disconshow()
        stopHeartbeat()
        setSocketFlag(false)

      })
      val.onMessage((err) => {
        const { data: body } = err
        const data = JSON.parse(body)
        const { messageType, content = {}, forbidden } = data
        const { type } = content
        if (type === 'remove') {
          setVisibleSuspende(false)
        }
        else if (messageType === 'addBlackListUser') {
          let timeOut = setTimeout(() => {
            goBack()
            clearTimeout(timeOut)
          }, 3000)
          toast('您已被拉黑，3秒后退出直播间')
        }
        else if (forbidden === '1') {
          toast('您已被禁言')
          // setForbiddenFlag(forbiddenFlag)
        }
        else if (messageType === 'livedata' || messageType === 'liveStatus') {
          if (messageType === 'liveStatus') {
            setLiveInfo({
              ...content
            })
          }
          setUseData((e) => {
            return {
              ...e,
              ...content
            }
          })
        }
        else if (messageType === 'teacher' && type === 'goods') {
          setVisibleSuspende({
            show: true,
            detail: data
          })
        }
        else if (messageType === 'removeUser' || messageType === 'heartBeat') {
          return null
        }
        else if (messageType === 'lotteryNotify') {
          const { lotteryDetail } = data
          setGiftVisible(() => {
            return {
              show: true
            }
          })
          setLotteryData(lotteryDetail)
        }
        else if (messageType === 'lotteryPrize') {
          setGiftVisible(false)
          setLotteryData((e) => {
            setPirzeVisible({
              show: true,
              detail: data,
              lotteryInfo: e
            })
            return {}
          })

        }
        setMessages((e) => {
          return [...e, data];
        });
      })
      val.onClose((err) => {
        const { code } = err
        if (code === 1000) {
          stopHeartbeat()
          setSocketFlag(false)
        } else {
          stopHeartbeat()
          setSocketFlag(false)
          setTimeout(() => {
            disconnect()
            connect()
          }, 1000)
        }
      })

    })

  };
  const handleInputChange = (e) => {
    setInputValue(e.detail.value);
  };
  const disconnect = () => {
    Taro.closeSocket({
      success: (e) => {
      }
    })
  };
  const disconshow = () => {
    Taro.closeSocket({
      code: 3001
    })
  };
  const handleSendMessage = () => {
    if (inputValue.trim() !== '') {
      Taro.sendSocketMessage({
        data: JSON.stringify({ goodsType, lotteryId: lotteryInfo.id, appointFlag: appointFlag ? '1' : '0', sessionId: session, unionId, userSession: session, senderType: 'user', goodsId, username, profile, messageType: 'student', organizationId, device: 'miniProgram', token, content: { text: inputValue, type: 'text' } }),
        success: () => {
          setInputValue('');
          setAppointFlag(false)
        },
        fall: () => {
          toast('发送失败')
        }
      })
    }
  };
  const heartBeatStart = () => {
    headerTime = setInterval(() => {
      Taro.sendSocketMessage({
        data: JSON.stringify({ goodsType, sessionId: session, unionId, userSession: session, senderType: 'user', goodsId, username, profile, messageType: 'heartBeat', organizationId, device: 'miniProgram', token }),
        success: () => {
        },
        fall: () => {
          // toast('发送失败')
        }
      })
    }, 5000);
  }
  const stopHeartbeat = () => {
    clearInterval(headerTime);
  }

  const renderActive = {
    hd: <RenderChatRoom connect={connect} socketFalg={socketFalg} session={session} goodsId={goodsId} renderStyle={renderStyle} renderSelf={renderSelf} messages={messages} goodsType={goodsType}></RenderChatRoom>,
    yy: <Invitation onShare={() => setVisibleShare(true)} active={active} organizationId={organizationId} goodsId={goodsId}></Invitation>,
    js: <View className='liveInteraction_content'>
      <RichText nodes={formatRichText(content)}></RichText>


    </View>,
    materialInfo: <AtAccordion
      open={materialInfoVisible}
      onClick={() => setMaterialInfoVisible(!materialInfoVisible)}
      title='资料列表'
    >
      <AtList hasBorder={false}>
        {materialInfoList.map((item, index) => {
          const { materialName, contentType, content } = item
          const { url } = JSON.parse(content);
          return <AtListItem
            onClick={() => handleLink(contentType, url)}
            key={index}
            title={materialName}
            iconInfo={{ value: renderIcon(contentType, url) }}
          />
        })}
      </AtList>
    </AtAccordion>
  }[active]
  console.log(playerList[videoPlayIndex])
  const renderVideo = () => {
    if (playerList.length > 0) {
      return <Video
        id={'livePlayer_info'}
        objectFit={renderSelf === 'hp' ? 'fillCrop' : "contain"}
        orientation={'vertical'}
        direction={screenType === 'horizontal' ? 90 : 0}
        onEnded={() => {

          if (videoPlayIndex < playerList.length - 1) {
            setVideoPlayIndex(videoPlayIndex + 1)
          }
          else {
            setVideoPlayIndex(0)
          }
        }}

        onRrror={() => {
          setPlayerRead(false)
        }} style={{ width: '100%', height: '100%', zIndex: '10!important', position: 'static' }}
        src={playerList[videoPlayIndex]}
        mode='live'
        autoplay={true}
      >
        {renderSelf === 'hp' && <>
          <HorizontalUi fetchList={fetchList} setToolPopVisible={setToolPopVisible} liveObjStatus={liveObjStatus} handleInputChange={handleInputChange} inputValue={inputValue} renderStyle={renderStyle} handleSendMessage={handleSendMessage} useData={useData} account={account} data={data} setVisibleShare={setVisibleShare} setLive_default={setLive_default}></HorizontalUi>
          {renderStyle !== 'default' ? <RenderChatRoom connect={connect} socketFalg={socketFalg} session={session} goodsId={goodsId} renderStyle={renderStyle} renderSelf={renderSelf} messages={messages} goodsType={goodsType}></RenderChatRoom> : null}
          <ShareImageComponent hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} renderStyle={renderStyle} onOpenDrop={() => setRecommendationVisible({ show: true })} visible={visibleShare} onClose={(e) => setVisibleShare(e)} data={{ ...goodsBaseInfo, ...directLiveInfo }}></ShareImageComponent>
          <MaskGift
            hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
            onOpen={() => {
              setLotteryVisible(() => {
                setGiftVisible(false)
                return true
              })
            }}
            onClose={() => setGiftVisible(false)}
            visible={giftVisible}
          ></MaskGift>
          <Recommendation hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} visible={recommendationVisible} onClose={() => setRecommendationVisible(false)}></Recommendation>
          <MaskPeople hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} visible={peopleVisible} onClose={() => { setPeopleVisible(false) }}></MaskPeople>
          <MaskPrize
            hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
            onLinkPeople={() => {
              setPeopleVisible(prizeVisible)
            }} unionId={unionId} visible={prizeVisible} onClose={() => { setPirzeVisible(false) }}></MaskPrize>
          <ToolPop
            hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
            onShare={() => {
              setVisibleShare(() => {
                setToolPopVisible(false)
                return true
              })
            }} visible={toolPopVisible} onClose={() => setToolPopVisible(false)}></ToolPop>
          <SuspendedGoods hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} formData={{ fromGoodsType: goodsType, fromGoodsId: goodsId }} visible={visibleSuspende} onClose={() => setVisibleSuspende(false)} ></SuspendedGoods>
          <Contain hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} formData={{ fromGoodsType: goodsType, fromGoodsId: goodsId }} visible={visible} onClose={() => setVisible(false)}></Contain>
          <Lottery
            renderStyle={renderStyle}
            hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
            onhandleMessage={(e) => {
              if (!e) {
                setInputValue(() => {
                  setAppointFlag(true)
                  setLotteryVisible(false)
                  return e
                })
              }
              else {
                Taro.sendSocketMessage({
                  data: JSON.stringify({ lotteryId: lotteryInfo.id, appointFlag: '1', sessionId: session, userSession: session, unionId, senderType: 'user', goodsId, username, profile, messageType: 'student', organizationId, device: 'miniProgram', token, content: { text: e, type: 'text' } }),
                  success: () => {
                    setLotteryVisible(() => {
                      return false
                    })
                  },
                  fall: () => {
                    toast('发送失败')
                  }
                })
              }
            }}
            onShare={() => setVisibleShare(true)}
            onOpen={() => {
              setLotteryVisible(true)
            }}
            visible={LotteryVisible}
            onClose={() => setLotteryVisible(false)}
            goodsId={goodsId}
            data={lotteryData}
          ></Lottery>
          <MaskCollection
            hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
            visible={collection} onClose={(e) => {
              setCollection({
                ...collection,
                show: false
              })
            }} ></MaskCollection>
        </>}
      </Video>
    }
    else {
      return <View style={{ ...backgroundObj(warmUp), width: '100%', height: '100%' }}>
        <View className='liveInteraction_live_getOut'>
          <View className='liveInteraction_live_outOne'> 请您耐心等待
          </View>
          <View>直播回放正在生成中。。。</View>
        </View>
      </View>
    }
  }
  const handleLive = () => {
    const live = Taro.createLivePlayerContext('livePlayer_info')
    if (renderStyle !== 'qp') {
      if (screenType === 'horizontal') {
        live.requestFullScreen({
          direction: 90,
          success: () => {
            setRenderStyle(() => {
              setRenderSelft('hp')
              return 'qp'
            })
          }
        })
      }
      else {
        setRenderStyle(() => {
          setRenderSelft('sp')
          return 'qp'
        })
      }
    }
    else {
      return
    }
  }
  const setLive_default = () => {
    const live = Taro.createLivePlayerContext('livePlayer_info')
    live.exitFullScreen({
      success: () => {
        setRenderStyle(() => {
          setRenderSelft('sp')
          return 'default'
        })
      }
    })
  }
  if (check === '1') {
    return <View></View>
  }
  return (
    <View className={renderStyle === 'default' ? "liveInteraction_box" : renderSelf === 'sp' ? "liveInteraction_box liveInteraction_sp" : 'liveInteraction_box liveInteraction_hp'}>
      {renderSelf !== 'hp' && <>
        <ShareImageComponent hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} renderStyle={renderStyle} onOpenDrop={() => setRecommendationVisible({ show: true })} visible={visibleShare} onClose={(e) => setVisibleShare(e)} data={{ ...goodsBaseInfo, ...directLiveInfo }}></ShareImageComponent>
        <MaskGift
          hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
          onOpen={() => {
            setLotteryVisible(() => {
              setGiftVisible(false)
              return true
            })
          }}
          onClose={() => setGiftVisible(false)}
          visible={giftVisible}
        ></MaskGift>
        <Recommendation hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} visible={recommendationVisible} onClose={() => setRecommendationVisible(false)}></Recommendation>
        <MaskPeople hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} visible={peopleVisible} onClose={() => { setPeopleVisible(false) }}></MaskPeople>
        <MaskPrize
          hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
          onLinkPeople={() => {
            setPeopleVisible(prizeVisible)
          }} unionId={unionId} visible={prizeVisible} onClose={() => { setPirzeVisible(false) }}></MaskPrize>
        <ToolPop
          hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
          onShare={() => {
            setVisibleShare(() => {
              setToolPopVisible(false)
              return true
            })
          }} visible={toolPopVisible} onClose={() => setToolPopVisible(false)}></ToolPop>
        <SuspendedGoods hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} formData={{ fromGoodsType: goodsType, fromGoodsId: goodsId }} visible={visibleSuspende} onClose={() => setVisibleSuspende(false)} ></SuspendedGoods>
        <Contain hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'} formData={{ fromGoodsType: goodsType, fromGoodsId: goodsId }} visible={visible} onClose={() => setVisible(false)}></Contain>
        <Lottery
          renderStyle={renderStyle}
          hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
          onhandleMessage={(e) => {
            if (!e) {
              setInputValue(() => {
                setAppointFlag(true)
                setLotteryVisible(false)
                return e
              })
            }
            else {
              Taro.sendSocketMessage({
                data: JSON.stringify({ lotteryId: lotteryInfo.id, appointFlag: '1', sessionId: session, userSession: session, unionId, senderType: 'user', goodsId, username, profile, messageType: 'student', organizationId, device: 'miniProgram', token, content: { text: e, type: 'text' } }),
                success: () => {
                  setLotteryVisible(() => {
                    return false
                  })
                },
                fall: () => {
                  toast('发送失败')
                }
              })
            }
          }}
          onShare={() => setVisibleShare(true)}
          onOpen={() => {
            setLotteryVisible(true)
          }}
          visible={LotteryVisible}
          onClose={() => setLotteryVisible(false)}
          goodsId={goodsId}
          data={lotteryData}
        ></Lottery>
        <MaskCollection
          hpFlag={renderStyle === 'qp' && renderSelf === 'hp' ? '1' : '0'}
          visible={collection} onClose={(e) => {
            setCollection({
              ...collection,
              show: false
            })
          }} ></MaskCollection>
      </>}

      <View className={renderStyle === 'default' ? "liveInteraction_live_box" : renderSelf === 'sp' ? "liveInteraction_sp_box" : 'liveInteraction_hp_box'}>
        {renderVideo()}
        {/* 
        {renderSelf !== 'hp' ? renderStyle === 'default' && active !== 'hd' ? null : token ? <View className="liveInteraction_bottom">
          <Input
            value={inputValue}
            placeholder='快来发表你的感想吧'
            onInput={handleInputChange}
            disabled={true}
            className="liveInteraction_input"
          />
          <Text className='liveInteraction_Outline' onClick={() => setToolPopVisible({ show: true })}></Text>
          <Text className='liveInteraction_OutShop' onClick={fetchList}>{commerceGoodsAmount}</Text>
          <Text className='liveInteraction_Send' onClick={handleSendMessage}></Text>
       
        </View> : <View className="liveInteraction_bottom">
          <View onClick={() => Router('login')}><Text style={{ color: '#FF6B4D' }}>登录</Text>发弹幕，参与主播互动</View>
        
        </View> : null} */}

      </View>
      <Tab
        list={list.filter(item => {
          const { show = true } = item
          return show
        })}
        value={active}
        onChange={(e) => {
          setActive(e);
        }}
      ></Tab>
      {renderActive}
    </View>
  )
};
export default LiveInteraction